<?php
class SupplierDispatchReturnsController extends AppController {
    var $name = 'SupplierDispatchReturns';

    var $viewPath = 'suppliers/returns/dispatch_returns';

    var $pageTitle = 'Dispatch Return Information';

    var $uses = array('SDRH','SDR', 'SDH', 'DispatchStatus', 'CustStockIn', 'Product', 'ProductSerial', 'RunningNo', 'UserCoH');

    var $paginate = array(
        'SDRH' => array(
            'order' => 'SDRH.id DESC'
        )
    );

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'main_supplier_returns');
        $this->set('tabMenu', 'tabmenus/supplier/returns');
    }

    function display() {
        parent::display('SDRH');
        $this->paginate['SDRH']['contain'] = array('Customer', 'Site', 'SDH');

        $this->_checkSupplier('SDRH');
        $this->_checkCustomerOnHand('SDRH');

        $this->_paging('SDRH');
    }

   function save() {
        $is_success = true;
        $drh_id = null;
        if ($this->data['mode'] == 'add') {
            $is_success = $this->_save_return();
        } else { // mode == 'edit'
            $this->SDRH->id = $this->data['SDRH']['id'];
            $is_success = $this->SDRH->saveField('remark', $this->data['SDRH']['remark']);
            $is_success &= $this->SDRH->saveField('collector_id', $this->Auth->user('id'));
        }

        if ($is_success) {
            $drh_id = $this->SDRH->id;
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Save fail !", 'flash/fail');
        }

        $this->data['SDR'] = null;
        $this->setAction('view', $drh_id);
    }

    function _save_return() {
        $drh_id = null;
        $is_success = true;
        // ตรวจสอบว่ามีรายการเข้ามาหรือไม่
        if (!empty($this->data['SDRH']['supplier_dispatch_head_id'])) {
            $this->SDRH->query("BEGIN");;

            // กำหนดข้อมูล SDH Return Head
            // Generate return no
            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::SUPPLIER_DISPATCH_RETURNS, $year, null, 5);
            $this->data['SDRH']['return_no'] = 'DSR' . $year . '1' . $runno;
            $this->data['SDRH']['collector_id'] = $this->Auth->user('id');
            $this->data['SDRH']['supplier_id'] = $this->Auth->user('supplier_id');
            if($this->SDRH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                // update SDH ว่ามีการ Return
                $this->SDH->id = $this->data['SDRH']['supplier_dispatch_head_id'];
                $this->SDH->saveField('is_dispatch_return', true);
                // ถ้าเป็น On SDH เปลี่ยนเป็น Cancel
                if ($this->data['dispatch_status_id'] == DispatchStatus::ON_DISPATCH_STATUS) {
                    $this->SDH->saveField('dispatch_status_id', DispatchStatus::CANCEL_STATUS);
                }

                $drh_id = $this->SDRH->id;
            } else {
                $is_success = false;
            }
            if ($is_success) {
                $this->SDRH->query("COMMIT");;
            } else {
                $this->passedArgs['supplier_dispatch_head_id'] = $this->data['SDRH']['supplier_dispatch_head_id'];
                $this->SDRH->query("ROLLBACK");
            }
        } else {
            $this->data = null;
            return false;
        }
        return $is_success;
    }

    function view($id = null) {
        // edit หรือมาจากหน้า dispatch
        if ($id != null) {
            $this->SDRH->contain(array('Customer', 'Site', 'SDH', 'Supplier', 'SDR' => array('Product' => array('Unit'), 'CustProductSite')));

            if (isset($this->passedArgs['return_dispatch_id'])) {
                $this->data = $this->SDRH->findBySupplierDispatchHeadId($this->passedArgs['return_dispatch_id']);
            } else {
                $this->data = $this->SDRH->findById($id);
            }

            $this->_neighbors($id, $this->SDRH, array('fields' => array('id')));
            $this->set('mode', 'edit');
        } else {
            // ดึงรายการ SDH ที่ Partial หรือ On Dispatch ที่ยังไม่ได้ทำการ Return
            $customers = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));
            $this->set('dispatches', $this->SDH->find('list', array(
                        'conditions' => array(
                            'dispatch_status_id' => array(
                                DispatchStatus::ON_DISPATCH_STATUS,
                                DispatchStatus::PARTIAL_CONSIGNED_STATUS
                            ),
                            'is_dispatch_return' => null,
                            'supplier_id' => $this->Auth->user('supplier_id'),
                            'customer_id' => $customers
                        )
                    )
                )
            );

            if (isset($this->passedArgs['supplier_dispatch_head_id'])) {
                $this->SDH->contain(array('Customer', 'Site', 
                        'SD' => array(
                            'Product' => array('Unit'), 'CustProductSite',
                            'conditions' => array(
                                'SD.qty != SD.stock_in_qty'
                            )
                        )
                    )
                );
                $this->data = $this->SDH->findById($this->passedArgs['supplier_dispatch_head_id']);
            }

            $this->set('mode', 'add');
            $this->set('return_by', $this->Auth->user('name'));
            $this->set('today', date("d/m/Y"));                 
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->SDRH->contain(array('Customer', 'Site', 'SDH', 'Supplier', 'SDR' => array('Product' => array('Unit'), 'CustProductSite')));
        $this->data = $this->SDRH->findById($id);
    }
}
?>